﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SF.Code.Extension.ControlsHelper;

namespace SG.Browser.Chrome.VerticalTabs
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
        {
            listBox1.InvokeEx(pList => UpdateChromeTabs(pList, e.FullPath));
        }

        private void UpdateChromeTabs(ListBox box, string file)
        {

            box.Items.Clear();
            var lines = File.ReadAllLines(file, Encoding.UTF8); 
            var info = lines.First().Split('\t');

            try
            {
                File.Delete(file);
            }
            catch
            {

            }

            if (info.Length == 1)
            {
                // this is an close event    
            }
            else if (info.Length == 4)
            {
                switch (info[0])
                {
                    case "activate":
                        var name = info[1];
                        var pid = int.Parse(info[2]);
                        var window = Convert.ToUInt32(info[3], 16);
                        box.Items.Add(name + " - " + pid + " - " + window);

                        User32.EnumChildWindows(new IntPtr(window), (p1, p2) =>
                                                                        {
                                                                            box.Items.Add(string.Format("p1: {0} p2: {1}", p1, p2));
                                                                            var text = new StringBuilder(256);
                                                                            User32.GetWindowText(p1, text, 255);

                                                                            box.Items.Add(text);
                                                                            return true;
                                                                        }, IntPtr.Zero);
                        break;
                }
            }
        }
    }
}
